package com.sitech.util.spring;

import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverConnectionFactory;
import org.apache.commons.dbcp.SQLNestedException;

import com.sitech.ibnms.util.DesEncrypterIsmp;

public class DataSourceImpl extends BasicDataSource {

	protected ConnectionFactory createConnectionFactory()
	    throws SQLException
	{
	    Class driverFromCCL = null;
	    if(driverClassName != null)
	        try
	        {
	            try
	            {
	                if(driverClassLoader == null)
	                    Class.forName(driverClassName);
	                else
	                    Class.forName(driverClassName, true, driverClassLoader);
	            }
	            catch(ClassNotFoundException cnfe)
	            {
	                driverFromCCL = Thread.currentThread().getContextClassLoader().loadClass(driverClassName);
	            }
	        }
	        catch(Throwable t)
	        {
	            String message = "Cannot load JDBC driver class '" + driverClassName + "'";
	            logWriter.println(message);
	            t.printStackTrace(logWriter);
	            throw new SQLNestedException(message, t);
	        }
	    Driver driver = null;
	    try
	    {
	        if(driverFromCCL == null)
	        {
	            driver = DriverManager.getDriver(url);
	        } else
	        {
	            driver = (Driver)driverFromCCL.newInstance();
	            if(!driver.acceptsURL(url))
	                throw new SQLException("No suitable driver", "08001");
	        }
	    }
	    catch(Throwable t)
	    {
	        String message = "Cannot create JDBC driver of class '" + (driverClassName == null ? "" : driverClassName) + "' for connect URL '" + url + "'";
	        logWriter.println(message);
	        t.printStackTrace(logWriter);
	        throw new SQLNestedException(message, t);
	    }
	    if(validationQuery == null)
	    {
	        setTestOnBorrow(false);
	        setTestOnReturn(false);
	        setTestWhileIdle(false);
	    }
	    String user = username;
	    if(user != null)
	        connectionProperties.put("user", user);
	    else
	        log("DBCP DataSource configured without a 'username'");
	    String pwd = password;
	    if(pwd != null){
	    	DesEncrypterIsmp encrypter = new DesEncrypterIsmp();
			pwd = encrypter.decrypt(pwd);
	        connectionProperties.put("password", pwd);
	    }else
	        log("DBCP DataSource configured without a 'password'");
	    ConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, url, connectionProperties);
	    return driverConnectionFactory;
	}
}
